package com.leyou.upload.service.impl;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.domain.ThumbImageConfig;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.upload.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author linzx
 * @date 2020/3/25
 */
@Service
@Slf4j
public class UploadServiceImpl implements UploadService {

    private static final List<String> CONTENT_TYPES = Arrays.asList("image/jpeg","image/gif");

   private static  final String SERVICE_WEB_PREFIX = "http://image.leyou.com/" ;


    @Autowired
    private FastFileStorageClient storageClient ;
    @Autowired
    private ThumbImageConfig thumbImageConfig;

    @Override
    public String upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String contentType = file.getContentType();
        if (!CONTENT_TYPES.contains(contentType)) {
            log.info("文件类型不合法:{}",originalFilename);
            return null;
        }
        try {
            BufferedImage read = ImageIO.read(file.getInputStream());
            if (read == null) {
                log.info("文件类型不合法:{}",originalFilename);
                return null;
            }

            String ext = StringUtils.substringAfterLast(originalFilename, ".");
            StorePath path = storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);
            return SERVICE_WEB_PREFIX + path.getFullPath() ;
        } catch (IOException e) {
            log.error("文件读取失败:{}" ,e.getMessage());
        }

        return null;
    }
}
